<?php
/**
 * FlashMessage class file.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright  Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

/**
 * Flash message widget allows for displaying flash messages to the user.
 */
class FlashMessage extends CWidget
{
	/**
	 * @property array the keys for which to get flash messages.
	 */
	public $keys;
	/**
	 * @property string the template to use for displaying flash messages.
	 */
	public $template='<div class="{key}">{message}</div>';
	/**
	 * @property array the html options.
	 */
	public $htmlOptions=array();

	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		$assetPath = Yii::app()->assetManager->publish(dirname(__FILE__).'/assets', false, -1, true);
		Yii::app()->clientScript->registerCoreScript('jquery');
		Yii::app()->clientScript->registerCoreScript('jquery.ui');
		Yii::app()->clientScript->registerScriptFile($assetPath.'/jquery.flashmessage.js');
	}

	/**
	 * Runs the widget.
	 */
	public function run()
	{
		$id = $this->getId();

		if (isset($this->htmlOptions['id']))
			$id = $this->htmlOptions['id'];
		else
			$this->htmlOptions['id']=$id;

		if (is_string($this->keys))
			$this->keys=array($this->keys);

		$markup = '';
		foreach ($this->keys as $key)
		{
			if (Yii::app()->user->hasFlash($key))
			{
				$markup .= strtr($this->template,array(
					'{key}'=>$key,
					'{message}'=>Yii::app()->user->getFlash($key),
				));
			}
		}

		echo CHtml::openTag('div',$this->htmlOptions);
		echo $markup;
		echo CHtml::closeTag('div');

		Yii::app()->clientScript->registerScript(__CLASS__.'#'.$id,"
			var element = jQuery('#{$id}');
			
			element.flashmessage({
				keys: ".CJavaScript::encode($this->keys).",
				template: '{$this->template}'
			});
		",CClientScript::POS_READY);
	}
}